<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import  patientList  from "@/mock/patientData"; // 导入真实病人数据
import { graphic } from "echarts/core";
import { ElMessage } from "element-plus";

const option = ref({});

// 计算风险分层统计数据
const riskStatistics = computed(() => {
  const stats = {
    低危: 0,
    中危: 0,
    高危: 0,
    极高危: 0
  };
  
  patientList.forEach(patient => {
    if (stats.hasOwnProperty(patient.riskLevel)) {
      stats[patient.riskLevel as keyof typeof stats]++;
    }
  });
  
  return {
    category: ["低危", "中危", "高危", "极高危"],
    riskData: [
      stats.低危,
      stats.中危,
      stats.高危,
      stats.极高危
    ]
  };
});

// 计算医院分布统计数据
const hospitalStatistics = computed(() => {
  const stats = {
    "智绘心康": 0,
    "首都医科大学附属北京安贞医院": 0,
    "首都医科大学附属北京潞河医院": 0
  };
  
  patientList.forEach(patient => {
    if (stats.hasOwnProperty(patient.hospital)) {
      stats[patient.hospital as keyof typeof stats]++;
    }
  });
  
  return {
    category: ["智绘心康", "安贞医院", "潞河医院"],
    hospitalData: [
      stats["智绘心康"],
      stats["首都医科大学附属北京安贞医院"],
      stats["首都医科大学附属北京潞河医院"]
    ]
  };
});

const getData = () => {
  try {
    console.log("患者风险分层统计", riskStatistics.value);
    console.log("医院分布统计", hospitalStatistics.value);
    
    // 使用真实数据设置图表
    setOption(riskStatistics.value);
    
  } catch (err) {
    console.error("加载患者数据失败:", err);
    ElMessage.error("加载患者数据失败");
  }
};

const setOption = async (newData: any) => {
  option.value = {
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(0,0,0,.6)",
      borderColor: "rgba(147, 235, 248, .8)",
      textStyle: {
        color: "#FFF",
      },
      formatter: function (params: any) {
        var result = params[0].name + "<br>";
        params.forEach(function (item: any) {
          if (item.value) {
            result += item.marker + " " + item.seriesName + " : " + item.value + "人</br>";
          } else {
            result += item.marker + " " + item.seriesName + " :  - </br>";
          }
        });
        return result;
      },
    },
    title: {
      text: "患者风险分层分布",
      textStyle: {
        color: "#B4B4B4",
        fontSize: 16,
        fontWeight: "bold"
      },
      left: "center",
      top: "0"
    },
    grid: {
      left: "50px",
      right: "40px",
      bottom: "30px",
      top: "60px", // 为标题留出更多空间
    },
    xAxis: {
      data: newData.category,
      axisLine: {
        lineStyle: {
          color: "#B4B4B4",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#B4B4B4",
        fontSize: 12
      }
    },
    yAxis: {
      type: "value",
      name: "人数",
      nameTextStyle: {
        color: "#B4B4B4"
      },
      splitLine: {
        lineStyle: {
          color: "rgba(180, 180, 180, 0.3)",
          type: "dashed"
        }
      },
      axisLine: {
        lineStyle: {
          color: "#B4B4B4",
        },
      },
      axisLabel: {
        color: "#B4B4B4",
        formatter: "{value}"
      },
    },
    series: [
      {
        name: "患者人数",
        type: "bar",
        barWidth: 30,
        // 根据风险等级设置不同颜色
        itemStyle: {
          borderRadius: 5,
          color: function(params: any) {
            const colors = [
              new graphic.LinearGradient(0, 0, 0, 1, [ // 低危 - 绿色
                { offset: 0, color: "#4ECDC4" },
                { offset: 1, color: "#A3E4D7" }
              ]),
              new graphic.LinearGradient(0, 0, 0, 1, [ // 中危 - 黄色
                { offset: 0, color: "#FFD93D" },
                { offset: 1, color: "#FFFA8D" }
              ]),
              new graphic.LinearGradient(0, 0, 0, 1, [ // 高危 - 橙色
                { offset: 0, color: "#FF9F43" },
                { offset: 1, color: "#FFC785" }
              ]),
              new graphic.LinearGradient(0, 0, 0, 1, [ // 极高危 - 红色
                { offset: 0, color: "#FF6B6B" },
                { offset: 1, color: "#FFA8A8" }
              ])
            ];
            return colors[params.dataIndex] || colors[0];
          }
        },
        label: {
          show: true,
          position: "top",
          color: "#FFF",
          fontWeight: "bold",
          formatter: "{c}人"
        },
        data: newData.riskData
      }
    ]
  };
};

// 切换到医院分布图表
const showHospitalDistribution = () => {
  option.value = {
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(0,0,0,.6)",
      borderColor: "rgba(147, 235, 248, .8)",
      textStyle: {
        color: "#FFF",
      },
    },
    title: {
      text: "患者医院分布",
      textStyle: {
        color: "#B4B4B4",
        fontSize: 16,
        fontWeight: "bold"
      },
      left: "center",
      top: "0"
    },
    grid: {
      left: "50px",
      right: "40px",
      bottom: "30px",
      top: "60px",
    },
    xAxis: {
      data: hospitalStatistics.value.category,
      axisLine: {
        lineStyle: {
          color: "#B4B4B4",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#B4B4B4",
        fontSize: 12,
        interval: 0 // 强制显示所有标签
      }
    },
    yAxis: {
      type: "value",
      name: "人数",
      nameTextStyle: {
        color: "#B4B4B4"
      },
      splitLine: {
        lineStyle: {
          color: "rgba(180, 180, 180, 0.3)",
          type: "dashed"
        }
      },
      axisLine: {
        lineStyle: {
          color: "#B4B4B4",
        },
      },
      axisLabel: {
        color: "#B4B4B4",
        formatter: "{value}"
      },
    },
    series: [
      {
        name: "患者人数",
        type: "bar",
        barWidth: 30,
        itemStyle: {
          borderRadius: 5,
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#1890FF" },
            { offset: 1, color: "#36CFC9" }
          ])
        },
        label: {
          show: true,
          position: "top",
          color: "#FFF",
          fontWeight: "bold",
          formatter: "{c}人"
        },
        data: hospitalStatistics.value.hospitalData
      }
    ]
  };
};

// 切换回风险分层图表
const showRiskDistribution = () => {
  setOption(riskStatistics.value);
};

onMounted(() => {
  getData();
});
</script>

<template>
  <div class="chart-container">
    <div class="chart-controls">
      <button @click="showRiskDistribution" class="chart-btn active">风险分层</button>
      <button @click="showHospitalDistribution" class="chart-btn">医院分布</button>
    </div>
    <v-chart class="chart" :option="option" v-if="JSON.stringify(option) != '{}'" />
  </div>
</template>

<style scoped lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-controls {
  display: flex;
  justify-content: center;
  gap: 10px;
  padding: 10px 0;
}

.chart-btn {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #B4B4B4;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
  }
  
  &.active {
    background: $primary-color;
    color: #FFF;
    border-color: $primary-color;
  }
}

.chart {
  flex: 1;
  width: 100%;
}
</style>